package com.hmall.gateway.filters;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    
    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    // hutool工具包中用于判断请求路径与路径pattern是否匹配的工具
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request
        ServerHttpRequest request = exchange.getRequest();

        // 判断该请求是否需要登录拦截，不需要则放行
        // 判断逻辑独立成成员方法
        if(isExcluded(request.getPath().toString())){
            // 放行
            return chain.filter(exchange);
        }

        // 获取header中的token
        List<String> headers = request.getHeaders().get("authorization");
        if (CollUtil.isEmpty(headers)) {
            return chain.filter(exchange);
        }
        String token = headers.get(0);

        Long userId = null;
        // 解析token
        try {
            userId = jwtTool.parseToken(token);
        }catch (UnauthorizedException e){
            // 校验失败，需要返回401状态码 注意！不是放行
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // setComplete会直接返回而不会调用接下来的过滤器了
        }

        // 将用户信息保存到header上
        String userIdStr = userId.toString();
        // 使用mutate之后记得要使用build生成新的exchange！！
        ServerWebExchange newExchange = exchange
                .mutate()
                .request(re -> re.header("user-info", userIdStr))
                .build();

        // 放行（使用新的带用户信息的exchange）
        return chain.filter(newExchange);
    }

    private boolean isExcluded(String string) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, string)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
